import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;

import javax.swing.JOptionPane;
/**
* The class Bot
* @author Kamil Olejnik
*/

public class Bot extends Client
{
	    private int round;
	    private int stake;
	    private int maxBet;
	    private boolean folded=false;

	    private int[] botHand;
	    private String reducedHandSet;
	    private int reducedHandLength;
	    private int reducedHandWorstCardRank;

	    private int botStartingCoins = -1;
	    private int botCoins;
	    private int botBet;
	    private PlayerInfo[] arrayOfPlayers;
	    private int numbersOfAddedPlayers = 0;
	    
	    /**
    *   @param port Port of game
    *   @param adres Adres of name
    *   @param name name of Bot
    *   @throws ClientException if bot couldn't connect
    */
	    public Bot(int port, String adres, String name)throws ClientException {
            super(port, adres, name);
	        arrayOfPlayers = new PlayerInfo[6];
	        botHand = new int[4];
	        
	    	sendStartGame();
	    }
	    /**
    *   ACtion performed method
    *  @param enabledButtons possible actions in game at the moment
    *
    */
	    private void performAction(String enabledButtons) {
	        try{
	            sleep(10);
	        }catch (InterruptedException e) {

	        }
	        if(enabledButtons.equals("CF")) {
	            send("Bet_" +  Integer.toString(maxBet - botBet));
	        }
	        else if(enabledButtons.equals("H")) {
	            send("Check_");
	        }
	        else if(enabledButtons.equals("CRF")) {
	            send("Bet_" +  Integer.toString(maxBet - botBet));
	        }
	        else if(enabledButtons.equals("FA")) {
	            send("Fold_");
	        }
	        else if(enabledButtons.equals("RF")) {
	            if(reducedHandLength == 4 || (reducedHandLength == 3 && reducedHandWorstCardRank <7))
	                send("Bet_" +  Integer.toString(maxBet + 10));
	            else
	            {
	            	folded =true;
	                send("Fold_");
	            }
	        }
	        else if(enabledButtons.equals("HBF")) {
	            send("Check_");
	        }
	        else if(enabledButtons.equals("HF")) {
	            send("Check_");
	        }
	        else if(enabledButtons.equals("E")) {
	            System.out.println("** Changed cards: " + getCardSetForExhange(reducedHandSet) + " **");
	            send("Exchange_" + getCardSetForExhange(reducedHandSet));
	        }
	    }
	    /**
    * Choosing set of cards to exhange
    * @param cards Cards in Hand
    * @return cardSet set of cards 
    */
	    public String getCardSetForExhange(String cards) {
	        String cardSet = "";
	        System.out.println(cards);
	        while(!cards.equals("")) {
	            if(cards.startsWith("1")) {
	                cardSet += 0;
	            }
	            else if(cards.startsWith("0")) {
	                cardSet += 1;
	            }
	            cards = cards.substring(1);
	            while(cardSet.length()<4)
	            	cardSet = cardSet + "0";
	        }
	        return cardSet;
	    }  
	    

public void ClientList(String list){
	System.out.println(list);
	String[] PlayersList;
   	PlayersList = list.split(" ");
   	for(int i =0; i<PlayersList.length; i++)
   	{
   		if(	this.arrayOfPlayers[i] == null)
   		{
   			this.arrayOfPlayers[i] = new PlayerInfo(PlayersList[i],i);
   					
   		}
   	}       	
}

   	 
public void Chat(String msg)
{
    System.out.println(msg);
}

public void bigBlind(String value)
{
	botBet =0;
	int playerId = Integer.parseInt(value.substring(0,1));
    int blind = Integer.parseInt(value.substring(1));
    maxBet = blind;
    if(this.Id == playerId) {
          botBet = blind;
    }
    else {
    		if(arrayOfPlayers[playerId]!= null)
    		{
                arrayOfPlayers[playerId].setBigBlind(true);
                arrayOfPlayers[playerId].setCurrentBet(blind);
    		}
    		else
    			System.out.println("ERROR");

            }
}

public void smallBlind(String value)
    	{
	int playerId = Integer.parseInt(value.substring(0,1));
    String blind = value.substring(1);
    if(this.Id == playerId) {
          botBet = Integer.parseInt(blind);
    }
    else {
    		if(arrayOfPlayers[playerId]!= null)
    		{
                arrayOfPlayers[playerId].setSmallBlind(true);
                arrayOfPlayers[playerId].setCurrentBet(Integer.parseInt(blind));
    		}
    		else
    			System.out.println("ERROR");

}
    	}
public void cards(String cards)
	{
    System.out.print("** ");
    for(int i = 0; i < 4; i++) {
        botHand[i] = Integer.parseInt(cards.substring(2*i,2+2*i));
        System.out.print(botHand[i]);
    }
    System.out.println(" **");
    reducedHandLength = Hand.getReducedHand(botHand).length;
    reducedHandSet = Hand.getReducedHandCardSet(botHand);
    reducedHandWorstCardRank = Hand.giveWorstCard(Hand.getReducedHand(botHand));
    System.out.println("** Reduced Hand Set: " + reducedHandSet + " **");
}
public void sCoins(String value)
{
	 int playerId = Integer.parseInt(value.substring(0, 1));
     String amount = value.substring(1);
     if (playerId == Id) {
         if(botStartingCoins == -1) {
             botStartingCoins = Integer.parseInt(amount);
             System.out.println("** Coins = " + botStartingCoins + " **");
         }
         botCoins = Integer.parseInt(amount);
     }
     else {

         if(arrayOfPlayers[playerId] != null)
        	          arrayOfPlayers[playerId].setTotalCoins(Integer.parseInt(amount));
             else
                 System.out.println("ERROR");
             
         }

     }
public void bet(String value)
{
    int playerId = Integer.parseInt(value.substring(0,1));
    int bet = Integer.parseInt(value.substring(1));
    if(bet > maxBet) {
        maxBet = bet;
    }
    if (playerId == Id) {
        botBet = bet;
    }
    else {
    	if(arrayOfPlayers[playerId] != null)
    	{
    		 arrayOfPlayers[playerId].setValueOfRise(maxBet - bet);
    		 System.out.println(arrayOfPlayers[playerId].getName() + " rised " + (maxBet - bet));
             arrayOfPlayers[playerId].setCurrentBet(bet);
    	}
    	else
                System.out.println("ERROR");

        }
}


public void enable(String buttons)
{
	if(!folded)
	 performAction(buttons);
}
public void dFold(String player)
{
    int playerId = Integer.parseInt(player);
    if (Id != playerId) {
    	if(arrayOfPlayers[playerId] != null)
    		arrayOfPlayers[playerId].setFolded(true);
    	else
           System.out.println("ERROR");
    }
}
public void dAllin(String Id)
{
	  int playerId = Integer.parseInt(Id);
      if (playerId != this.Id) {
          if(arrayOfPlayers[playerId] != null)
        	  arrayOfPlayers[playerId].setAllIn(true);
          else
          System.out.println("ERROR");
       }
}
public void stake(String stake)
{
    this.stake = Integer.parseInt(stake);
}
public void round(String round)
{
	System.out.println(round);
    this.round = Integer.parseInt(round);
} 
public void Stop()
{
	System.out.println("Stop");
}
public void WaitForPlayers()
{
	System.out.println("WaitForPlayers");
}
public void PlayerDisconected(String p)
{
	System.out.println(p +" is disconected");
}
public void StartCards(String cards)
{
    System.out.print("** ");
    for(int i = 0; i < 4; i++) {
        botHand[i] = Integer.parseInt(cards.substring(2*i,2+2*i));
        System.out.print(botHand[i]);
    }
    System.out.println(" **");
    reducedHandLength = Hand.getReducedHand(botHand).length;
    reducedHandSet = Hand.getReducedHandCardSet(botHand);
    reducedHandWorstCardRank = Hand.giveWorstCard(Hand.getReducedHand(botHand));
    System.out.println("** Reduced Hand Set: " + reducedHandSet + " **");
	
}
public void StartCoins(String coins)
{
             botStartingCoins = Integer.parseInt(coins);
             System.out.println("** Coins = " + botStartingCoins + " **");
}
public void GameStart()
{
	System.out.println("Game is started");
}
public void PlayerNotRejecting(String player)
{
	System.out.println(player+" isn't rejected");
}
public void PlayerRejecting(String player)
{
	int i = -1;
	try{
		
		i = Integer.parseInt(player);
		}
		catch(NumberFormatException e)
	{
		System.out.println("Error Invalid Player Number");
	}
		if(i == Id)
		{
			System.out.println("YouAreRejected");
			System.exit(0);
		}

}
public void ProposalToReject(String player)
{
	int i = -1;
	try{
		
		i = Integer.parseInt(player);
		}
		catch(NumberFormatException e)
	{
		System.out.println("Error Invalid Player Number");
	}
	
	if (i == this.Id)
	{
		System.out.println("Once from other Players don't want play with You");
	}

		this.send("reject_1");
	
}
public void Wait(String player)
{
	System.out.println("Wait");
}
public void Error(String e)
{
	System.out.println(e);
}
public void Winner(String Winners)
{
	folded = false;
	System.out.println("Winners"+Winners);
}
public void out()
{
	this.works = false;
	System.exit(0);
	
}
public static void main(String[] args) {
		int port = 0;
		String adres = "";
		String nick = "";
		try{
		     port = Integer.parseInt(args[0]);
		}
		catch(NumberFormatException e)
		{
			System.err.println("Invalid port");
			System.exit(1);
		}
		if(args[1]!=null)
			adres = args[1];
		else{
			System.err.println("Invalid adres");
			System.exit(1);
		}
		if(args[2]!=null)
			nick = args[2];
		else{
			nick = "Player";
		}
		Bot client = null;
		try{
			client = new Bot(port ,adres ,nick);
		}
		catch(ClientException e){
            System.out.println("Socket problem");
            JOptionPane.showMessageDialog(null, "You cannot join the game\non this port" ,
                            "Error", JOptionPane.ERROR_MESSAGE);
            System.exit(1);
		}
		if(client != null)
		client.start();


	}

}